
'use strict';
const crypto = require("crypto");
const moment = require('moment');
const request = require("request");
module.exports = {
    //生成签名的随机串
    createNoce() {
        let str = 'axka6s4glgbv3zcdfgfdsdfdlklkldf';
        var len = 32
        var strlength = str.length
        var ss = "";
        for (var i = 0; i < len; i++) {
            ss += str.charAt(Math.floor(Math.random() * strlength));
        }
        return ss;
    },
    //生成时间戳
    createTime() {
        return parseInt(new Date().getTime() / 1000, 10).toString();
    },
    //签名
    _sing(noncestr, jsapi_ticket, timestamp, url) {
        let params = {
            'noncestr': noncestr,
            'jsapi_ticket': jsapi_ticket,
            'timestamp': timestamp,
            'url': url
        };
        let str = raw(params);
        let shasum = crypto.createHash('sha1');
        return shasum.update(str, 'utf8').digest('hex')
    },
    //再次签名
    sing(ticket, url) {
        let nocestr = this.createNoce();
        let timestamp = this.createTime();
        let singnature = this._sing(nocestr, ticket, timestamp, url);
        return {
            nocestr,
            timestamp,
            singnature
        }
    },
    //小程序解密运动数据
    aesDecrypt(key, iv, crypted) {
        try {
            key = new Buffer(key, 'base64')
            encryptedData = new Buffer(crypted, 'base64')
            iv = new Buffer(iv, 'base64')
            const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv)
            decipher.setAutoPadding(true)
            let decoded = decipher.update(crypted, 'base64', 'utf8')
            decoded += decipher.final('utf8');
            let array = JSON.parse(decoded).stepInfoList;
            let newarr = [];
            for (let index = 0; index < array.length; index++) {
                array[index].timestamp = moment(array[index].timestamp * 1000).utcOffset(8).format('YYYY-MM-DD');
            }
            return { stepInfoList: array }
        } catch (error) {
            console.log(error)
        }
    },
    //小程序获取用户sessionkey
    getSessionKey(code, appid, appsecret) {
        return new Promise((resolve, reject) => {
            request({
                url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`,
                method: "GET",
                json: true
            }, function (error, response, body) {
                if (response.statusCode == 200) {
                    resolve(body);
                } else {
                    reject(error)
                }
            });
        })
    },
    //小程序解密手机号码
    getPhoneNumber(key, iv, crypted) {
        return new Promise((resolve, reject) => {
            try {
                key = new Buffer(key, 'base64')
                encryptedData = new Buffer(crypted, 'base64')
                iv = new Buffer(iv, 'base64')
                const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv)
                decipher.setAutoPadding(true)
                let decoded = decipher.update(crypted, 'base64', 'utf8')
                decoded += decipher.final('utf8');
                let array = JSON.parse(decoded);
                resolve(array);
            } catch (error) {
                reject(error)
            }
        })
    },
};


//字典排序
function raw(args) {
    var keys = Object.keys(args);
    keys = keys.sort()
    var newArgs = {};
    keys.forEach(function (key) {
        newArgs[key] = args[key];
    });
    var string = '';
    for (var k in newArgs) {
        string += '&' + k + '=' + newArgs[k];
    }
    string = string.substr(1);
    //console.log(string);  
    return string;
};
